package com.qiaoya.nettyConnProxy;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.qiaoya.model.entity.WatchCommandEntity;
import com.qiaoya.service.HealthDataService;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

@Component
public class AKXWatchProtocolDecoder {
	@Autowired
	protected HealthDataService healthDataService;
	
	private static AKXWatchProtocolDecoder protocolDecoder;
	
	@PostConstruct     //关键二   通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
    public void init() {  
		protocolDecoder = this;  
		protocolDecoder.healthDataService = this.healthDataService;   // 初使化时将已静态化的testService实例化
    }  

	public static void processPacketHandler(String strCommand, ChannelHandlerContext session) {
		if ("".equals(strCommand) || strCommand == null) {
			return;
		}
		String[] command = strCommand.split(":", 7);
		if (command.length < 6) {
			return;
		}
		WatchCommandEntity recvCommand = new WatchCommandEntity(command);
		String commandType = recvCommand.getCommandType();
		if ("T1".equalsIgnoreCase(commandType)) {// 终端登录watch login
			// TODO:1.验证手表是否已经注册？2.通过验证的返回登录成功，未登录通过的失败，并切断连接
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S1");
			ArrayList<String> ayy = new ArrayList<String>();
			if (ayy != null) {
				ayy.add("1");
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
				ayy.add(df.format(new Date()));
			}
			sendCommand.setParameters(ayy);
			System.out.println("S1,return to T1:" + sendCommand.toString());
			try {
				session.writeAndFlush(getSendByteBuf(sendCommand.toString()));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

		} else if ("T2".equalsIgnoreCase(commandType)) {// 连接心跳connect Heart
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S2");
			ArrayList<String> ayy = sendCommand.getParameters();
			String location = "";
			String strLBS = ayy.get(1);
			String timstamp = ayy.get(2);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			long lt = new Long(Long.parseLong(timstamp));
			Date date = new Date(lt * 1000L);
			String strTime = simpleDateFormat.format(date);// 测量的时间
			location = protocolDecoder.healthDataService.insertLBS(sendCommand.getImei(), strLBS, strTime, 1);
			ayy.clear();
			// TODO:根据坐标返回详细地址信息
			ayy.add(location.replaceAll(" ", ""));
			sendCommand.setCommandType("S2");
			sendCommand.setParameters(ayy);
			System.out.println("S2,return to T2:" + sendCommand.toString());
			// session.write(sendCommand.toString());
			try {
				session.writeAndFlush(getSendByteBuf(sendCommand.toString()));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

		} else if ("T5".equalsIgnoreCase(commandType)) {// 终端应答获取实时脉搏请求，answer
														// to heartbeat requestc
			return;
		} else if ("T28".equalsIgnoreCase(commandType)) {// 终端上传脉搏数据，watch
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S28");
			ArrayList<String> ayy = sendCommand.getParameters();
			if (ayy != null) {
				if ("1".equalsIgnoreCase(ayy.get(0))) {// 实时数据
					// String strPulse = ayy.get(1);
					// String timstamp = ayy.get(2);
					// SimpleDateFormat simpleDateFormat = new
					// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					// long lt = new Long(Long.parseLong(timstamp));
					// Date date = new Date(lt*1000L);
					// String strTime = simpleDateFormat.format(date);// 测量的时间
					// //// TODO:实时数据处理
					// System.out.println(strPulse.split("\\|")[0]);
					// serverHandler.healthDataService.insertPulse(sendCommand.getImei(),
					// strPulse.split("\\|")[0], strTime, 0);

				} else if ("2".equalsIgnoreCase(ayy.get(0))) {// 定时数据
					String strPulse = ayy.get(1);
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt * 1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间
					// TODO:定时数据处理
					protocolDecoder.healthDataService.insertPulse(sendCommand.getImei(), strPulse, strTime, 0);
				} else if ("3".equalsIgnoreCase(ayy.get(0))) {// 手动数据
					// String strPulse = ayy.get(1);
					// String timstamp = ayy.get(2);
					// SimpleDateFormat simpleDateFormat = new
					// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					// long lt = new Long(Long.parseLong(timstamp));
					// Date date = new Date(lt*1000L);
					// String strTime = simpleDateFormat.format(date);// 测量的时间
					// //TODO:手动数据处理
					// serverHandler.healthDataService.insertPulse(sendCommand.getImei(),
					// strPulse, strTime, 0);
				} else if ("4".equalsIgnoreCase(ayy.get(0))) {// 睡眠数据
					String strPulse = ayy.get(1);
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt * 1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间
					// TODO:睡眠数据处理
					protocolDecoder.healthDataService.insertPulse(sendCommand.getImei(), strPulse, strTime, 0);
				}
				ayy.clear();
			}
			// session.write(sendCommand.toString());
			try {
				session.writeAndFlush(getSendByteBuf(sendCommand.toString()));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else if ("T13".equalsIgnoreCase(commandType)) {// 终端应答实时LBS请求，answer
															// to LBS request
			return;
		} else if ("T29".equalsIgnoreCase(commandType)) {// 终端上传LBS数据指令, watch
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S29");
			ArrayList<String> ayy = sendCommand.getParameters();
			String location = "";
			if (ayy != null) {
				if ("1".equalsIgnoreCase(ayy.get(0))) {// 实时数据
					String strLBS = ayy.get(1);
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt * 1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间
					location = protocolDecoder.healthDataService.insertLBS(sendCommand.getImei(), strLBS, strTime, 1);
				} else if ("2".equalsIgnoreCase(ayy.get(0))) {// 定时数据
					String strLBS = ayy.get(1);
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt * 1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间
					location = protocolDecoder.healthDataService.insertLBS(sendCommand.getImei(), strLBS, strTime, 1);
				} else if ("3".equalsIgnoreCase(ayy.get(0))) {// 代表实时wifi数据
					String strWifi = ayy.get(1);
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt * 1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间
					location = protocolDecoder.healthDataService.insertWifi(sendCommand.getImei(), strWifi, strTime, 1);
				} else if ("4".equalsIgnoreCase(ayy.get(0))) {// 实时gps数据
					String strGPS = ayy.get(1);
					String[] strstrGPSData = strGPS.split("\\|");
					String strLongitude = strstrGPSData[0];
					String strLatitude = strstrGPSData[1];
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt * 1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间
					protocolDecoder.healthDataService.insertGPS(sendCommand.getImei(), strLongitude, strLatitude,
							strTime, 1);
				} else if ("5".equalsIgnoreCase(ayy.get(0))) {// gps防盗数据
					String strGPS = ayy.get(1);
					String[] strstrGPSData = strGPS.split("\\|");
					String strLongitude = strstrGPSData[0];
					String strLatitude = strstrGPSData[1];
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt * 1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间
					protocolDecoder.healthDataService.insertGPS(sendCommand.getImei(), strLongitude, strLatitude,
							strTime, 1);
				} else if ("6".equalsIgnoreCase(ayy.get(0))) {// sos定位数据
					// ????
				}
				ayy.clear();
				// 根据坐标返回详细地址信息
				ayy.add(location.replaceAll(" ", ""));
				sendCommand.setParameters(ayy);
			}
			System.out.println("S29,return to T29:" + sendCommand.toString());
			// session.write(getUTF8String(sendCommand.toString()));
			try {
				session.writeAndFlush(getSendByteBuf(sendCommand.toString()));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else if ("T50".equalsIgnoreCase(commandType)) {// 终端综合数据（计步/LBS/脉搏）定时上传指令
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S50");
			ArrayList<String> ayy = sendCommand.getParameters();
			if (ayy.isEmpty() || ayy.size() < 7) {
				ayy.clear();
				System.out.println("S50,return to T50:" + sendCommand.toString());
				// session.write(sendCommand.toString());
				try {
					session.writeAndFlush(getSendByteBuf(sendCommand.toString()));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				return;
			}
			String strStep = ayy.get(1);
			String strLBS = ayy.get(4);
			String strPulse = ayy.get(5);
			String timstamp = ayy.get(6);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			long lt = new Long(Long.parseLong(timstamp));
			Date date = new Date(lt * 1000L);
			String strTime = simpleDateFormat.format(date);// 测量的时间
			// 20170712 综合数据的定位数据格式有错误
			// if(!strLBS.equals(null) && !strLBS.equals("")){
			// //insert LBS
			// serverHandler.healthDataService.insertLBS(sendCommand.getImei(),
			// strLBS, strTime, 1);
			// }
			if (!strPulse.equals(null) && !strPulse.equals("")) {
				// insert pulse
				protocolDecoder.healthDataService.insertPulse(sendCommand.getImei(), strPulse, strTime, 0);
			}
			if (!strStep.equals(null) && !strStep.equals("") && !strStep.equals("0|0|0|0|0|0|0|0|0|0|0|0|0")) {
				// insert pulse
				protocolDecoder.healthDataService.insertStep(sendCommand.getImei(), strStep, strTime, 3);
			}
			ayy.clear();
			System.out.println("S50,return to T50:" + sendCommand.toString());
			// session.write(sendCommand.toString());
			try {
				session.writeAndFlush(getSendByteBuf(sendCommand.toString()));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else if ("T45".equalsIgnoreCase(commandType)) {// 终端上传血压数据指令
			//：{1:1:0:232322: 39238239329: T45:67,89,64,434344}
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S45");
			ArrayList<String> ayy = sendCommand.getParameters();
			if (ayy != null) {
				String systolic = ayy.get(0);
				String diastolic = ayy.get(1);
				String timstamp = ayy.get(3);
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				long lt = new Long(Long.parseLong(timstamp));
				Date date = new Date(lt * 1000L);
				String strTime = simpleDateFormat.format(date);// 测量的时间
				protocolDecoder.healthDataService.insertBloodPress(sendCommand.getImei(),systolic,diastolic, strTime, 2);
				
				ayy.clear();
			}
			// session.write(sendCommand.toString());
			try {
				System.out.println("S45,return to T45:" + sendCommand.toString());
				session.writeAndFlush(getSendByteBuf(sendCommand.toString()));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			

		} else if ("T47".equalsIgnoreCase(commandType)) {// 终端获取天气指令

		} else if ("T18".equalsIgnoreCase(commandType)) {// 终端应答设置sos号码指令

		} else if ("T38".equalsIgnoreCase(commandType)) {// 终端应答设置步履年龄体重指令

		} else if ("T49".equalsIgnoreCase(commandType)) {// 终端回复语音对讲指令

		} else if ("T8".equalsIgnoreCase(commandType)) {// 终端回复分段定时指令

		} else if ("T51".equalsIgnoreCase(commandType)) {// 终端上传关机指令

		} else if ("T52".equalsIgnoreCase(commandType)) {// 终端回复设置脉搏安全阈值

		} else if ("T4".equalsIgnoreCase(commandType)) {// 终端回复设置地址指令

		} else if ("T53".equalsIgnoreCase(commandType)) {// 终端回复手表提醒指令

		} else if ("T61".equalsIgnoreCase(commandType)) {// 终端回复关注和点赞设置指令

		} else if ("T55".equalsIgnoreCase(commandType)) {// 终端回复消息指令

		} else if ("T56".equalsIgnoreCase(commandType)) {// 终端上传消息已读指令

		} else if ("T57".equalsIgnoreCase(commandType)) {// 终端回复设置电话号码指令

		} else if ("T58".equalsIgnoreCase(commandType)) {// 终端回复界面设置指令

		} else if ("T59".equalsIgnoreCase(commandType)) {// 终端上传血糖数据指令

		} else if ("T60".equalsIgnoreCase(commandType)) {// 终端回复积分设置指令

		} else if ("T64".equalsIgnoreCase(commandType)) {// 终端回复积分设置指令

		} else if ("T63".equalsIgnoreCase(commandType)) {// 终端发送消息指令

		} else if ("T65".equalsIgnoreCase(commandType)) {// 终端获取积分，关注，点赞数据指令

		} else if ("T66".equalsIgnoreCase(commandType)) {// 终端回复设置终端时钟界面指令

		} else if ("T68".equalsIgnoreCase(commandType)) {// 终端回复设置防盗指令指令

		} else if ("T69".equalsIgnoreCase(commandType)) {// 终端应答实时温度和紫外线上传指令指令

		} else if ("T70".equalsIgnoreCase(commandType)) {// 终端应答工作模式设置指令指令

		} else if ("T71".equalsIgnoreCase(commandType)) {// 终端应答设置血压校准值指令指令

		} else if ("T72".equalsIgnoreCase(commandType)) {// 终端应答设置血压自动测量指令指令

		} else if ("T75".equalsIgnoreCase(commandType)) {// 终端开机图标指令

		} else if ("T65".equalsIgnoreCase(commandType)) {// 终端获取积分，关注，点赞数据指令

		} else {// 未知消息类型
			return;
		}
	}

	// public static String getUTF8String(String srcStr) {
	// // A StringBuffer Object
	// StringBuffer sb = new StringBuffer();
	// sb.append(srcStr);
	// String xmString="";
	// String strUTF8="";
	// try {
	// xmString = new String(sb.toString().getBytes("UTF-8"));
	// //strUTF8 = URLEncoder.encode(xmString, "UTF-8");
	// } catch (UnsupportedEncodingException e) {
	// e.printStackTrace();
	// }
	// return xmString;
	// }

	private static ByteBuf getSendByteBuf(String message) throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer();
		sb.append(message);
		//String xmString = "";
		ByteBuf pingMessage = Unpooled.buffer();
		try {
			//xmString = new String(sb.toString().getBytes("UTF-8"));
			byte[] req = sb.toString().getBytes("UTF-8");//xmString.getBytes("UTF-8");
			pingMessage.writeBytes(req);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return pingMessage;
	}
}
